<template>
	<view>
		<mg-popup v-model="showGg" :z-index="3000">
			<view v-if="loading" class="bs15 bf ggjz">
				<view class="dhtmd">
					<view class="bf6 jzi1"></view>
					<view class="bf6 jzi2 p3"></view>
					<view class="bf6 jzi2 p3"></view>
				</view>
			</view>
			<view v-else class="ggc bs15 bf posi-r">
				<view @click="showGg = false" class="ggx posi-a r0">
					<text class="iconfont iconyx f56"></text>
				</view>
				<view class="ggtop f-row">
					<view class="ggh mr30 f-g-0 bs20">
						<mg-img :src="goodsInfo.icon"></mg-img>
					</view>
					<view>
						<view class="f36 wei">{{ goodsInfo.name }}</view>

						<view class="mt15 f24 c7">产品描述</view>
						<view class="mt15 f24 c9 t-o-e3 w100">{{ goodsInfo.body }}</view>
					</view>
				</view>
				<scroll-view scroll-y class="ggb p23">
					<view class="m20">
						<!-- <block v-if="goodsInfo.specsData.length">
              <view class="p15 c6">规格</view>
              <view class="f-raw">
                <view @click="specificationChange(_specification)" v-for="_specification in goodsInfo.specsData"
                  :key="_specification.id" class="specv t-o-e f26" :style="{
                    background: currentSpecIds.includes(_specification.id)
                      ? tColor
                      : '',
                    color: currentSpecIds.includes(_specification.id)
                      ? '#fff'
                      : '',
                  }">{{ _specification.specsName }}</view>
              </view>
            </block> -->
						<!-- 属性 -->
						<block v-if="goodsInfo.attrData.length">
							<view v-for="(_attr, _arrtIndex) in goodsInfo.attrData" :key="_arrtIndex" class="">
								<view class="p15 c6 f28">
									{{ _attr.attrName }}(最少選{{ _attr.minnum }}-最多選{{ _attr.maxnum }})
								</view>
								<view class="f-raw">
									<view v-for="_attrItem in _attr.attrStr" :key="_attrItem.id">
										<view @click="clickAttribute(_attr, _attrItem)" class="specv t-o-e f26" :style="{
                      background: isAttrCheckbox(_attrItem.name, _attr.id)
                        ? tColor
                        : '',
                      color: isAttrCheckbox(_attrItem.name, _attr.id)
                        ? '#fff'
                        : '',
                    }" v-if="_attrItem.name">{{ _attrItem.name }}</view>
									</view>
								</view>
							</view>
						</block>
						<block v-if="goodsInfo.meterialData.length">
							<view class="p15 c6">{{
                systemGood.custom.feedName || "加料"
                }}</view>
							<view class="f-raw">
								<view @click="clickMaterial(_meterial)"
									v-for="(_meterial, ci) in goodsInfo.meterialData" :key="ci" class="specv t-o-e f26"
									:style="{
                    background: isMaterialCheckbox(_meterial.id) ? tColor : '',
                    color: isMaterialCheckbox(_meterial.id) ? '#fff' : '',
                  }">{{ _meterial.materialName
                  }}<text class="ml10" :style="{
                    color: isMaterialCheckbox(_meterial.id) ? '#fff' : tColor,
                  }">{{ `${sl}${_meterial.SalesPrice}` }}</text></view>
							</view>
						</block>
					</view>
				</scroll-view>
				<view v-if="goodsInfo.id" class="posi-r ggf bf f-col f-x-ad">
					<view class="f-x-bt">
						<view class="f-g-1">
							<view class="f-raw" :style="{ color: tColor }">

								<text class="f34 wei mr20">{{ sl
                  }}{{
                    Number(
                      currentSpec[0].SalesPrice
                        ? currentSpec[0].SalesPrice
                        : goodsInfo.price
                    )
                  }}
									<text class="f24 nowei c9 ml10">(库存{{ currentSpec[0].SalesStock }})</text>
								</text>
								<text class="">{{ systemGood.custom.feedName || "加料" }}+{{
                  sl + allMaterialPrice
                }}</text>
							</view>
							<view class="f22 c9 t-o-e3"> {{ attrLabel
                }}{{ materialLabel }}
							</view>
						</view>

					</view>
					<button @click="onFinsh" :style="{ background: tColor }" class="w100 cf ggbtn mt10 f34 f-c">
						选好了
					</button>
				</view>
			</view>
		</mg-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from "vuex";
	import mgPopup from "@/components/common/popup.vue";
	import bkB from "@/components/common/block-b.vue";
	import utils from "@/common/utils.js";
	export default {
		name: "popup",
		components: {
			mgPopup,
			bkB,
		},
		props: {
			co: {
				type: Object,
				default: function() {
					return {};
				},
			},
			cname: {
				type: String,
				default: "",
			},
			value: {
				type: Boolean,
				default: false,
			},
			width: {
				type: String,
				default: "70%",
			},
			zindex: {
				type: Number,
				default: 999,
			},
			storeid: {
				type: String,
				default: "",
			},
			systemGood: {
				type: Object,
				default: function() {
					return {};
				},
			},
		},
		data() {
			return {
				loading: true,
				goodsInfo: {},
				// 所选属性
				selectAttr: [],
				// 当前选中规格
				currentSpec: [],
				// 选中的小料
				currrntMaterial: [],
			};
		},
		methods: {
			// 切换规格回调
			specificationChange(pi) {
				// 只能选择一个规格
				this.currentSpec.splice(0, 1, pi);
			},
			clickAttribute(_attrGroupInfo, _attrItem) { // 多选

				const _index = this.selectAttr.findIndex(
					(_arrt) => _arrt.name == _attrItem?.name
				);

				console.log('_attrGroupInfo', _attrGroupInfo)

				// 转换为数字进行比较，因为 minnum 和 maxnum 是字符串格式的数字
				const minnum = parseInt(_attrGroupInfo.minnum, 10);
				const maxnum = parseInt(_attrGroupInfo.maxnum, 10);

				// 统计与 newarr.id 相匹配的 currarr 元素数量
				const count = this.selectAttr.filter(item => item.id === _attrGroupInfo.id).length;



				//   如果有这个属性，就替换
				if (_index !== -1) {


					// 比较数量并输出提示信息
					if (count - 1 < minnum) {
						console.log(`警告：ID 为 ${_attrGroupInfo.id} 的元素数量 ${count} 不等于指定的最小数量 ${minnum}。`);
					}else {

						var newarr = this.selectAttr.filter(item => !(item.name === _attrItem?.name && item.id ===
							_attrGroupInfo?.id));
						this.selectAttr = newarr;

						console.log(`ID 为 ${_attrGroupInfo.id} 的元素数量 ${count} 符合指定的最小数量 ${minnum}。`);
					}

				} else {
			        
					if(count == maxnum)
					{
						this.clickAttributeold(_attrGroupInfo,_attrItem);
						return;
					}
					if (count+1 > maxnum) {


						console.log(`警告：ID 为 ${_attrGroupInfo.id} 的元素数量 ${count+1} 不等于指定的最大数量 ${maxnum}。`);
						return;
					}else if(count== minnum){
					} 
					this.selectAttr.push({
						name: _attrItem?.name,
						id: _attrGroupInfo?.id,
					});
				}


				// console.log('_attrItem',_attrItem)
				// console.log('_attrGroupInfo',_attrGroupInfo)
				// console.log('this.selectAttr',this.selectAttr);
			},
			clickAttributeold(_attrGroupInfo, _attrItem) {

				const _index = this.selectAttr.findIndex(
					(_arrt) => _arrt.id == _attrGroupInfo?.id
				);
				//   如果有这个属性，就替换
				if (_index !== -1) {
					this.selectAttr.splice(_index, 1, {
						name: _attrItem?.name,
						id: _attrGroupInfo?.id,
					});
				} else {
					this.selectAttr.push({
						name: _attrItem?.name,
						id: _attrGroupInfo?.id,
					});
				}
			},
			clickMaterial(_data) {
				const _index = this.currrntMaterial.findIndex((_m) => _m.id == _data?.id);
				if (_index !== -1) {
					this.currrntMaterial.splice(_index, 1);
				} else {
					this.currrntMaterial.push(_data);
				}
			},
			// 选好了规格
			onFinsh: utils.throttle(function(e) {
				//   原料价格
				const allMaterialPrice = this.currrntMaterial?.reduce(
					(prev, curr) => prev + curr.SalesPrice * 1,
					0
				);


				//   原料label
				const materialLabel = this.currrntMaterial
					?.map((e) => e.materialName)
					.join(",");

				//   获取当前所选规格信息
				const {
					SalesPrice,
					SalesStock = 999,
					specsName,
					vipPrice
				} =
				this.currentSpec[0];

				const _currentArrtNames = this.selectAttr?.map((e) => e.name).join(",");

				const _info = {
					// 当前选中数量
					ggnum: 1,
					// 主餐id
					id: this.goodsInfo.id,
					// 主餐名称
					name: this.goodsInfo.name,
					storeId: this.storeid,
					jldata: materialLabel,
					attribute: _currentArrtNames,
					// specsName: specsName,
					// 主餐价格
					SalesPrice: SalesPrice,
					// 主餐库存
					SalesStock: SalesStock,
					vipPrice: vipPrice,
					// 规格id
					// groupId: id,
					// 加料价格
					jlmoney: allMaterialPrice,
					// 主配价格，有规格价格取规格价格，没有取主餐价格
					price: SalesPrice || this.goodsInfo.price,

					material: this.currrntMaterial?.map((_m) => {
						return {
							materialId: _m.id,
							num: 1,
						};
					}),
					// 加料id
					jlids: this.currrntMaterial?.map((_m) => _m.id)?.join(","),
					/* 可选搭配分组 */
					goodGroupId: this.co.goodGroupId,
				};
				//判断购物车是否存在此商品
				let i;
				if (
					this.co.isSpecs != 1 &&
					this.co.isMaterial != 1 &&
					this.co.isAttr != 1
				) {
					i = this.carList.find((v) => v.goodsId == this.co.id);
				} else {
					i = this.carList.find(
						(v) =>
						v.goodsId == this.co.id &&
						v.groupId == specInfo.groupId &&
						v.materialIds == jlInfo.jlids &&
						v.attribute == sxInfo.attribute
					);
				}
				if (i) {
					// 限购判断
					if (
						this.co.maxNum > 0 &&
						Number(i.num) + Number(this.goodsInfo.ggnum) > this.co.maxNum
					) {
						return this.util.message(`此商品限购${this.co.maxNum}份`, 3);
					}
				} else {
					// 起售判断
					if (this.co.minNum > 1 && this.co.minNum > this.goodsInfo.ggnum) {
						return this.util.message(`此商品${this.co.minNum}份起购`, 3);
					}
					// 限购判断 购物车没有，想第一次添加
					if (this.co.maxNum > 0 && this.goodsInfo.ggnum > this.co.maxNum) {
						return this.util.message(`此商品限购${this.co.maxNum}份`, 3);
					}
				}
				//   let goods = Object.assign(
				//     {
				//       ggnum: this.goodsInfo.ggnum,
				//     },
				//     this.co,
				//     specInfo,
				//     sxInfo,
				//     jlInfo
				//   );

				console.log("确定负极！！", _info);
				//父级方法
				this.$emit("addeee", {
					g: _info,
					addwz: 1,
				});
				this.showGg = false;
			}, 300),
			// 属性是否选中
			isAttrCheckbox(name, id) {
				return (
					this.selectAttr.findIndex((_r) => _r.id == id && _r.name == name) != -1
				);
			},
			// 原料是否被选中
			isMaterialCheckbox(id) {
				return this.currrntMaterial.findIndex((_r) => _r.id == id) != -1;
			},
		},
		computed: {
			...mapState({
				carList: (state) => state.scarList.data || [],
			}),
			showGg: {
				get() {
					return this.value;
				},
				set(newVal) {
					this.$emit("input", newVal);
				},
			},
			// 当前所选规格id
			currentSpecIds() {
				return this.currentSpec.map((_c) => _c?.id);
			},
			// 选中原料展示label
			materialLabel() {
				const _materialName = this.currrntMaterial.map((_m) => _m.materialName);

				return _materialName && _materialName?.length > 0 && this.currentSpec.vipPrice > 0 ?
					"," + _materialName.join(",") :
					_materialName.join(",");
			},
			attrLabel() {
				const _attrName = this.selectAttr.map((_a) => _a.name);
				return _attrName && _attrName?.length > 0 && this.currentSpec.vipPrice > 0 ?
					"," + _attrName.join(",") + "+" :
					_attrName.join(",") + "+";
			},
			// 所有加料的价格
			allMaterialPrice() {
				return this.currrntMaterial.reduce((total, item) => {
					return total + item.SalesPrice * 1;
				}, 0);
			},
		},
		watch: {
			async value(newVal) {
				if (newVal) {

					//   selectAttr: [],
					// // 当前选中规格
					// currentSpec: [],
					// // 选中的小料
					// currrntMaterial: [],
					this.selectAttr.splice(0, this.selectAttr.length);
					this.currentSpec.splice(0, this.currentSpec.length);
					this.currrntMaterial.splice(0, this.currrntMaterial.length);
					this.loading = true;
					this.goodsInfo = {};
					let {
						data
					} = await this.util.request({
						url: this.api.ggxq,
						data: {
							id: this.co.id,
							storeId: this.storeid,
						},
					});

					this.goodsInfo = Object.assign({}, this.co, data, {
						ggnum: 1,
					});

					console.log('this.co', this.co)

					// 规格默认选第一个
					if (this.currentSpec.length === 0) {
						this.currentSpec.push({
							SalesPrice: this.co.price,
							SalesStock: 999,
							vipPrice: this.co.price,
						});
					}

					// 属性默认选中,并且默认制作多少个
					console.log('attrData', data?.attrData);

					if (this.selectAttr.length === 0) {
						data?.attrData?.forEach((_a) => {

							// 添加对象到 selectAttr
							for (let i = 0; i < _a.minnum; i++) {
								this.selectAttr.push({
									id: _a.id,
									name: _a.attrStr?.[i]?.name,
								});
							}


						});
					}

					console.log('attrDatathis.selectAttr', this.selectAttr);


					this.loading = false;
				}
			},
		},
	};
</script>

<style scoped lang="scss">
	.bs15 {
		border-radius: 30rpx 30rpx 0 0;
	}

	.f54 {
		font-size: 52rpx;
	}

	.ggjz {
		padding: 50rpx 50rpx 200rpx;
	}

	.jzi1 {
		height: 350rpx;
	}

	.jzi2 {
		margin-top: 50rpx;
	}

	.ggc {
		.ggx {
			padding: 20rpx 20rpx 40rpx 40rpx;
			opacity: 0.7;
		}

		.ggtop {
			padding: 40rpx 30rpx 0;
		}

		.ggh {
			width: 240rpx;
			height: 240rpx;
		}

		.ggb {
			max-height: calc(86vh - 233rpx - 280rpx);

			.specv {
				min-width: 185rpx;
				padding: 0 30rpx;
				height: 70rpx;
				border-radius: 8rpx;
				text-align: center;
				line-height: 70rpx;
				background: #f5f5f7;
				margin: 0 20rpx 20rpx 0;
			}
		}

		.ggf {
			box-shadow: 0 -2rpx 9rpx 2rpx rgba(221, 221, 221, 0.6);
			padding: 20rpx 36rpx;
			min-height: 153rpx;
		}

		.ggbtn {
			border-radius: 80rpx;
			height: 90rpx;
		}
	}

	@keyframes backOpacity {
		0% {
			opacity: 0.8;
		}

		50% {
			opacity: 0.6;
		}

		100% {
			opacity: 1;
		}
	}

	.dhtmd {
		animation: backOpacity 0.7s ease-in-out infinite;
	}
</style>